import consts from "../../js/const";
import {routerFilter} from '../../utils/routerFilter';
import util from '../../utils/util';
import Toast from '@vant/weapp/toast/toast';

routerFilter({

    /**
     * 页面的初始数据
     */
    data: {
        frontSideImageUrl: consts.getImageUrl("licensePlate-frontSide.png"),
        reverseSideImageUrl: consts.getImageUrl("licensePlate-reverseSide.png"),
        currentDate: new Date().getTime(),
        minDate: new Date(2000, 1, 1).getTime(),
        addCarExampleImageUrl:consts.getImageUrl("addCarExample.png")
    },
    /* 输入框聚焦显示车牌号键盘 */
    handleFocus: function (e) {
        this.setData({
            showKeyboard: true
        })
    },

    /* 车牌号键盘点击事件 */
    setNumber: function (e) {
        let data = this.data;
        let vehicleFile = data.vehicleFile = data.vehicleFile || {};
        vehicleFile.plateNum = e.detail.value;
        this.setData(data);
    },
    hideKeyboard(e) {
        wx.hideKeyboard();
    },
    /**
     * 生命周期函数--监听页面加载obtainVehicleLicenseInfo
     */
    onLoad: function (options) {
        let APC_LIST = [];
        for (let ii = 1; ii <= 55; ii++) {
            APC_LIST.push({name: ii});
        }
        this.setData({APC_LIST: APC_LIST});
        let that = this;
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on('acceptDataFromOpenerPage', function (data) {
            if (data) {
                that.setData(data);
            }
        });
        let initBaseConfig = function () {
            util.promise('/baseConfig/searchConfigByTypeCdes', [consts.VEHICLE_TYPE, consts.VEHICLE_ENERGY, consts.VEHICLE_USE_CHARACTER]).then(function (res) {
                if (res.data) {
                    for (let key in res.data) {
                        res.data[key].forEach(function (row) {
                            row.name = row.dcOptionsCn;
                            row.code = row.dcOptions;
                            row.className = row.isFavourite ? 'eyc-action-sheet-item-1' : 'eyc-action-sheet-item';
                        });
                    }

                    that.setData(res.data);
                }
            })
        };
        initBaseConfig();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        console.log('onready.............');
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        console.log('onshow...................');
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    selectVehicleConfig: function (event) {
        let data = this.data;
        let dataset = event.currentTarget.dataset;
        data[dataset.key] = false;
        data[dataset.code] = event.detail.dcOptions;
        data[dataset.name] = event.detail.dcOptionsCn;
        this.setData(data);
    },
    obtainVehicleLicenseInfo: function (e) {
        let that = this;
        let data = that.data;
        let vehicleLicenseInfo = e.detail;
        data.vehicleFile = data.vehicleFile || {};
        let front = e.currentTarget.dataset.front;
        if (!data.vehicleFile.plateNum && front === '0') {
            Toast('请先扫描行驶证正本~~');
            return;
        } else if (front === '0') {
            if (data.vehicleFile.plateNum !== vehicleLicenseInfo.plate_num_b.text) {
                Toast('副本行驶证跟正本行驶证不一致~~');
                return;
            }
        }
        data.vehicleFile.plateNum = vehicleLicenseInfo.plate_num ? vehicleLicenseInfo.plate_num.text : data.vehicleFile.plateNum ? data.vehicleFile.plateNum : null;
        data.vehicleFile.vehicleTypeNme = vehicleLicenseInfo.vehicle_type ? vehicleLicenseInfo.vehicle_type.text : data.vehicleFile.vehicleTypeNme ? data.vehicleFile.vehicleTypeNme : null;
        data.vehicleFile.apc = vehicleLicenseInfo.passengers_num ? parseInt(vehicleLicenseInfo.passengers_num.text.match(/\d+/g)) : data.vehicleFile.apc ? data.vehicleFile.apc : null;

        data.vehicleFile.useCharacterNme = vehicleLicenseInfo.use_character ? vehicleLicenseInfo.use_character.text : data.vehicleFile.useCharacterNme ? data.vehicleFile.useCharacterNme : null;
        data.vehicleFile.registerDt = vehicleLicenseInfo.register_date ? vehicleLicenseInfo.register_date.text : data.vehicleFile.registerDt ? data.vehicleFile.registerDt : null;
        data.vehicleFile.engineNum = vehicleLicenseInfo.engine_num ? vehicleLicenseInfo.engine_num.text : data.vehicleFile.engineNum ? data.vehicleFile.engineNum : null;
        data.vehicleFile.vin = vehicleLicenseInfo.vin ? vehicleLicenseInfo.vin.text : data.vehicleFile.vin ? data.vehicleFile.vin : null;
        data.vehicleFile.owner = vehicleLicenseInfo.owner ? vehicleLicenseInfo.owner.text : data.vehicleFile.owner ? data.vehicleFile.owner : null;
        data.vehicleFile.model = vehicleLicenseInfo.mode ? vehicleLicenseInfo.model.text : data.vehicleFile.model ? data.vehicleFile.model : null;
        data.vehicleFile.addr = vehicleLicenseInfo.addr ? vehicleLicenseInfo.addr.text : data.vehicleFile.addr ? data.vehicleFile.addr : null;
        data.vehicleFile.issueDt = vehicleLicenseInfo.issue_date ? vehicleLicenseInfo.issue_date.text : data.vehicleFile.issueDt ? data.vehicleFile.issueDt : null;
        data.vehicleFile.grossMass = vehicleLicenseInfo.total_quality ? parseInt(vehicleLicenseInfo.total_quality.text.match(/\d+/g)) : data.vehicleFile.grossMass ? data.vehicleFile.grossMass : null;
        data.vehicleFile.approvedLoad = vehicleLicenseInfo.load_quality ? parseInt(vehicleLicenseInfo.load_quality.text.match(/\d+/g)) : data.vehicleFile.approvedLoad ? data.vehicleFile.approvedLoad : null;
        data.vehicleFile.unladenMass = vehicleLicenseInfo.prepare_quality ? parseInt(vehicleLicenseInfo.prepare_quality.text.match(/\d+/g)) : data.vehicleFile.unladenMass ? data.vehicleFile.unladenMass : null;
        data.vehicleFile.tractionMass = vehicleLicenseInfo.lead_quality ? parseInt(vehicleLicenseInfo.lead_quality.text.match(/\d+/g)) : data.vehicleFile.tractionMass ? data.vehicleFile.tractionMass : null;
        if (vehicleLicenseInfo.overall_size) {
            let overallDimensions = vehicleLicenseInfo.overall_size.text.match(/\d+/g);
            data.vehicleFile.overallDimensionLength = overallDimensions[0];
            data.vehicleFile.overallDimensionWidth = overallDimensions[1];
            data.vehicleFile.overallDimensionHigth = overallDimensions[2];
        }
        that.setData(data);
    },
    insertOrUpdateVehicleFile: function (event) {
        let that = this;
        let vehicleFile = that.data.vehicleFile;
        vehicleFile.openid = util.getStorageSync(consts.cache_key.OPENID);
        vehicleFile.isActive = 1;
        if (!vehicleFile || !vehicleFile.plateNum) {
            Toast('请选择车辆~~');
            return;
        }
        if (!vehicleFile.vehicleTypeNme) {
            Toast('请选择车辆类型~~');
            return;
        }
        if (!vehicleFile.apc) {
            Toast('请输入核定载人数~~');
            return;
        }
        if (!vehicleFile.useCharacterNme) {
            Toast('请选择使用性质~~');
            return;
        }
        if (!vehicleFile.registerDt) {
            Toast('请选择注册日期~~');
            return;
        }
        if (!vehicleFile.energy) {
            Toast('请选择能源类型~~');
            return;
        }
        const eventChannel = this.getOpenerEventChannel();
        util.promise('/insertOrUpdateVehicleFile', vehicleFile).then(res => {
            if (res.data) {
                that.data.vehicleFile = res.data;
                eventChannel.emit('refreshVehicleFiles');
                Toast({
                    type: 'success',
                    message: '保存成功~~',
                    onClose: () => {
                        wx.navigateBack({ delta: 1 });
                    }
                });

            }
        });
    },
    chooseImage: function (event) {
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res) {
                // tempFilePath可以作为img标签的src属性显示图片
                const tempFilePaths = res.tempFilePaths;
                tempFilePaths.forEach(function (filePath) {
                    wx.uploadFile({
                        url: consts.HOST_NAME + '/wechat/uploadVehicleLicense',
                        filePath: filePath,
                        name: 'file',
                        header: {
                            'content-type': 'multipart/form-data',
                            cookie: wx.getStorageSync(consts.cache_key.sessionid)
                        },
                        formData: {
                            fileDir: '/vehicleLicense'
                        },
                        success: function (res) {
                            if (res.data) {
                                let data = JSON.parse(res.data);
                                if (data.msg && !data.data) {
                                    Toast(data.msg);
                                } else {
                                    util.promise('/obtainVehicleLicenseInfo', {
                                        userId: util.getStorageSync(consts.cache_key.USER_ID),
                                        fileDir: '/vehicleLicense',
                                        fileNme: data.data
                                    }).then(function (res) {
                                        console.log(res);
                                    })
                                }
                            }
                        }
                    })
                });

            }
        })
    },
    selectUseCharacter(event) {
        let that = this;
        let item = event.detail;
        if (!item.isFavourite) {
            Toast({
                type: 'success',
                message: '该业务还未开通~~',
                onClose: () => {
                    that.selectTerm(event);
                }
            });
        } else {
            that.selectTerm(event);
        }


    },
    closeAddCarExample() {
        this.setData({ showAddCarExample: false });
    }
});